
package com.etop.weiway.wxmanage.controller;
import com.alibaba.fastjson.JSON;
import com.etop.weiway.basic.controller.BaseController;
import com.etop.weiway.commons.annotation.AccountRequired;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.entity.*;
import com.etop.weiway.wxmanage.service.MassMessageService;
import com.etop.weiway.wxmanage.service.MaterialService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 群发消息管理控制器
 * @author Jessy
 */
@Controller
@RequestMapping("/wxmanager/mass")
public class MassMessageController extends BaseController {

    @Autowired
    private MassMessageService massMessageService;
    @Autowired
    private MaterialService materialService;

    /**
     * 群发菜单
     *
     * @param request
     * @param response
     * @param session
     * @param model
     * @return
     * @throws Exception
     */
    @AccountRequired
    @RequestMapping(value = "/list", produces = "text/html; charset=utf-8")
    public String listMassMsg(HttpServletRequest request, HttpServletResponse response, 
            HttpSession session, Model model) throws Exception {
        Pager<Mass> massPager = massMessageService.getMassByPager(new Pager<>(request, response), (int) session.getAttribute("currentAccoutId"));
        model.addAttribute("pager", massPager);
        return "home/wxmanage/base/mass/list";
    }


    /**
     * 根据id获取mass对象
     * @param id
     * @return
     * @throws Exception 
     */
    @ModelAttribute(value = "mass")
    public Mass getMass(@RequestParam(required = false) Integer id)
            throws Exception {
        if (id != null && id > 0) {
            return massMessageService.loadMass(id);
        } else {
            return new Mass();
        }
    }

    /**
     * 进入群发页面前的请求处理GET
     *
     * @param mass
     * @param model
     * @return
     * @throws Exception
     */
    @AccountRequired
    @RequestMapping(value = "/edit", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String massMsgEditForm(@ModelAttribute(value = "mass") Mass mass,Model model) throws Exception {
        model.addAttribute("mass", mass);
        //以下用于重新发送
        if(mass.getMaterialType()!=null){
            switch(mass.getMaterialType()){
                case "text":
                    MaterialText materialText = null;
                            if(mass.getMaterialId()!=null)
                                materialText =  materialService.loadMaterialText(mass.getMaterialId());
                            else{
                                materialText = new MaterialText();
                                materialText.setContent(mass.getContent());
                            }
                                model.addAttribute("materialText",materialText);
                            break;
                case "image":
                            model.addAttribute("materialImage", materialService.loadMaterialImage(mass.getMaterialId()));
                            break;
                case "video":
                            model.addAttribute("materialVideo", materialService.loadMaterialVideo(mass.getMaterialId()));
                            break;
                case "voice":
                            model.addAttribute("materialVoice", materialService.loadMaterialVoice(mass.getMaterialId()));
                            break;
                case "news":
                            model.addAttribute("materialNews", materialService.loadMaterialNews(mass.getMaterialId()));
                            break;
                case "mutinews":
                            MaterialMutinews materialMutinews = materialService.loadMaterialMutinews(mass.getMaterialId());
                            model.addAttribute("materialNewses", JSON.toJSONString(materialMutinews.getMaterialNewses(), true));
                            break;
                default: break;
            }
        }
        return "home/wxmanage/base/mass/edit";
    }


    /**
     * 获取用户分组
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getGroups", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String getGroups(HttpSession session) throws Exception {
        return massMessageService.getGroupListByAccountId((Integer)session.getAttribute("currentAccoutId"));
    }

    /**
     * 提交群发请求的处理POST
     * @param mass
     * @param request
     * @param session
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @AccountRequired
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    String massMsgEdit(Mass mass, HttpServletRequest request,
                        HttpSession session,RedirectAttributes redirectAttributes) throws Exception {
        User user = (User) session.getAttribute("user");
        String path = request.getServletContext().getRealPath("/");
        if(!path.endsWith("/"))
            path +="/";
        path += "home/wxmanage/upload/" + user.getId() + "/";
        String result = massMessageService.handleSendMassMsg(mass,(int)session.getAttribute("currentAccoutId"), path);
        if(result.startsWith("error")) {
            String[] msg = result.split(":");
            this.addMessage(redirectAttributes, ERROR, msg[1]);
            return "redirect:/wxmanager/mass/edit";
        } else
            this.addMessage(redirectAttributes,"success",result);
        return "redirect:/wxmanager/mass/list";
    }



    /**
     * 删除mass
     * @param id
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/delete_{id}", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String deleteMass(@PathVariable Integer id) throws Exception {
        massMessageService.deleteMassById(id);
        return "redirect:/wxmanager/mass/list";
    }

    /**
     * 页面素材名称链接控制跳转到对应的edit页面
     * @param id
     * @param materialType
     * @param model
     * @return
     * @throws Exception 
     */
    @AccountRequired
    @RequestMapping(value = "/materialEdit_{id}", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String materialOfMass(@PathVariable Integer id, String materialType, Model model) throws Exception {
        Mass mass = massMessageService.loadMass(id);
        switch (materialType) {
            case "text":
                MaterialText materialText = materialService.loadMaterialText(mass.getMaterialId());
                model.addAttribute("materialText", materialText);
                return "home/wxmanage/base/material/text/edit";
            case "news":
                MaterialNews materialNews = materialService.loadMaterialNews(mass.getMaterialId());
                model.addAttribute("materialNews", materialNews);
                return "home/wxmanage/base/material/news/edit";
            case "mutinews":
                MaterialMutinews materialMutinews = materialService.loadMaterialMutinews(mass.getMaterialId());
                model.addAttribute("materialMutinews", materialMutinews);
                System.out.println(JSON.toJSONString(materialMutinews));
                MaterialNews firstNews = materialService.getMutinews_firstNews(materialMutinews);
                List<MaterialNews> remainNewses = materialService.getMutinews_remainNewses(materialMutinews);
                model.addAttribute("firstNews", firstNews);
                model.addAttribute("remainNewses", remainNewses);
                return "home/wxmanage/base/material/mutinews/edit";
            case "image":
                MaterialImage materialImage = materialService.loadMaterialImage(mass.getMaterialId());
                model.addAttribute("materialImage", materialImage);
                return "home/wxmanage/base/material/image/edit";
            case "video":
                MaterialVideo materialVideo = materialService.loadMaterialVideo(mass.getMaterialId());
                model.addAttribute("materialVideo", materialVideo);
                return "home/wxmanage/base/material/video/edit";
            case "voice":
                MaterialVoice materialVoice = materialService.loadMaterialVoice(mass.getMaterialId());
                model.addAttribute("materialVoice", materialVoice);
                return "home/wxmanage/base/material/voice/edit";

        }
        return "redirect:/wxmanager/mass/list";
    }

    /**
     * 页面素材类型链接控制跳转到对应的素材list页面
     * @param id
     * @param materialType
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/materialList_{id}", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String materialListOfMass(@PathVariable Integer id, String materialType) throws Exception {
        Mass mass = massMessageService.loadMass(id);
        switch (materialType) {
            case "text":
                return "redirect:/wxmanager/material/text/list";
            case "news":
                return "redirect:/wxmanager/material/MaterialNews/list";
            case "mutinews":
                return "redirect:/wxmanager/material/MaterialMutinews/list";
            case "image":
                return "redirect:/wxmanager/material/image/list";
            case "video":
                return "redirect:/wxmanager/material/video/list";
            case "voice":
                return "redirect:/wxmanager/material/voice/list";

        }
        return "redirect:/wxmanager/mass/list";
    }
}
